package com.jilefojing.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.enums.ItemTypeEnumForSource;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.RCategorySource;
import com.jilefojing.beans.pojos.Statistics;
import com.jilefojing.beans.pojos.enhanced.EnhancedComment;
import com.jilefojing.beans.pojos.enhanced.EnhancedDCategory;
import com.jilefojing.beans.pojos.enhanced.EnhancedEVideo;
import com.jilefojing.beans.pojos.enhanced.EnhancedStatistics;
import com.jilefojing.beans.pojos.enhanced.EnhancedTag;
import com.jilefojing.beans.pojos.enhanced.base.BaseEnhanced;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.ICommentService;
import com.jilefojing.service.IEVideoService;
import com.jilefojing.service.ISourceService;
import com.jilefojing.service.IStatisticsService;
import com.jilefojing.service.ITagService;
import com.jilefojing.util.Detect;
import com.jilefojing.web.base.BaseWeb;
import com.jilefojing.web.convent.CommonConvent;

/**
 * 视频
 * 
 * @author jiangguoshun
 * 
 */
@Controller
@RequestMapping("video")
public class VideoWeb extends BaseWeb {
	@Autowired
	private IEVideoService eVideoService;
	@Autowired
	private ICommentService commentService;
	@Autowired
	private ITagService tagService;
	@Autowired
	private ISourceService sourceService;
	@Autowired
	private IStatisticsService statisticsService;

	@RequestMapping("list-tag-{tagId}/part.html")
	public String getTagVideoListPartPage(@PathVariable("tagId") long tagId, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}

		EnhancedTag enhancedTag = (EnhancedTag) tagService.getEnhanced(tagId, userContext);
		if (enhancedTag == null) {
			throw new UserContextException(ResponseEnum.TAG_NOT_EXIST);
		}
		request.setAttribute("tag", CommonConvent.convent2TagData(enhancedTag));

		Pagination<EnhancedEVideo> pagination = new Pagination<EnhancedEVideo>(page, 12, true);

		pagination = eVideoService.getPaginationByTagIdForActive(tagId, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems((List<EnhancedEVideo>) eVideoService.appendEnhancedCommons(pagination.getItems(), userContext));
			pagination.setItems(eVideoService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEVideo(pagination.getItems());

			request.setAttribute("pagination", pagination);
			request.setAttribute("videos", CommonConvent.convent2EVideoDatas(pagination.getItems()));
		}

		return "web/video/tag_video_list_part";
	}

	/**
	 * 获取视频列表 -- 标签获取
	 * 
	 * @param request
	 * @return
	 * @throws UserContextException
	 */
	@RequestMapping("list-tag-{tagId}.html")
	public String toTagVideoListPage(@PathVariable("tagId") long tagId, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}

		EnhancedTag enhancedTag = (EnhancedTag) tagService.getEnhanced(tagId, userContext);
		if (enhancedTag == null) {
			throw new UserContextException(ResponseEnum.TAG_NOT_EXIST);
		}
		request.setAttribute("tag", CommonConvent.convent2TagData(enhancedTag));

		Pagination<EnhancedEVideo> pagination = new Pagination<EnhancedEVideo>(page, 12, true);

		pagination = eVideoService.getPaginationByTagIdForActive(tagId, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems((List<EnhancedEVideo>) eVideoService.appendEnhancedCommons(pagination.getItems(), userContext));
			pagination.setItems(eVideoService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEVideo(pagination.getItems());

			request.setAttribute("pagination", pagination);
			request.setAttribute("videos", CommonConvent.convent2EVideoDatas(pagination.getItems()));
		}

		Pagination<EnhancedTag> hotEnhancedTagPagination = new Pagination<EnhancedTag>(1, 10, false);
		// 获取热门标签
		hotEnhancedTagPagination = tagService.getPaginationByItemTypesForHot(Arrays.asList(new ItemTypeEnumForSource[] { ItemTypeEnumForSource.VIDEO }), hotEnhancedTagPagination, userContext);
		if (Detect.notEmpty(hotEnhancedTagPagination.getItems())) {
			request.setAttribute("hotTags", CommonConvent.convent2TagDatas(hotEnhancedTagPagination.getItems()));
		}

		return "web/video/tag_video_list";
	}

	/**
	 * 分页获取的视频列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("list-part.html")
	public String getVideoListPart(HttpServletRequest request) {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		List<Long> categoryIds = this.getIds(request, "cat");

		short sort = 0;
		String sortStr = request.getParameter("sort");
		if (Detect.notEmpty(sortStr)) {
			sort = Short.valueOf(sortStr);
		}
		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}

		// cat=1~2~5-31~3~8 --->两种选择交集
		Pagination<EnhancedEVideo> pagination = new Pagination<EnhancedEVideo>(page, 24, true);
		if (sort == 1) {// 热门
			pagination.addOrder(new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC));
		} else if (sort == 2) {// 最近更新
			pagination.addOrder(new Order(RCategorySource.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		}

		pagination = eVideoService.getPaginationByCategoryIdsForActive(categoryIds, null, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eVideoService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEVideo(pagination.getItems());

			request.setAttribute("pagination", pagination);
			request.setAttribute("videos", CommonConvent.convent2EVideoDatas(pagination.getItems()));
		}

		return "web/video/video_list_part";
	}

	/**
	 * 获取视频列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("list.html")
	public String toVideoListPage(HttpServletRequest request) {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		// 加载视频分类
		List<EnhancedDCategory> enhancedDCategories = eVideoService.getEnhancedDCategories(userContext);
		request.setAttribute("dCategories", CommonConvent.convent2DCategoryDatas(enhancedDCategories));

		List<Long> categoryIds = this.getIds(request, "cat");

		// cat=1~2~5-31~3~8 --->两种选择交集
		Pagination<EnhancedEVideo> pagination = new Pagination<EnhancedEVideo>(1, 24, true);

		pagination = eVideoService.getPaginationByCategoryIdsForActive(categoryIds, null, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eVideoService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEVideo(pagination.getItems());

			request.setAttribute("pagination", pagination);
			request.setAttribute("videos", CommonConvent.convent2EVideoDatas(pagination.getItems()));
		}

		return "web/video/video_list";
	}

	private List<Long> getIds(HttpServletRequest request, String key) {
		String valsStr = request.getParameter(key);
		if (Detect.notEmpty(valsStr)) {
			String[] valStrs = valsStr.split("~");
			List<Long> valIds = new ArrayList<Long>();
			for (String valStr : valStrs) {
				valIds.add(Long.valueOf(valStr));
			}
			return valIds;
		}
		return null;
	}

	/**
	 * 获取视频播放页面
	 * 
	 * @param id
	 * @param request
	 * @return
	 * @throws UserContextException
	 */
	@RequestMapping("{id}.html")
	public String toVideoPage(@PathVariable("id") long id, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		EnhancedEVideo enhancedEVideo = eVideoService.getEnhancedForActive(id, userContext);
		if (userContext != null) {
			enhancedEVideo = (EnhancedEVideo) eVideoService.appendEnhancedExtralsForUser(enhancedEVideo, userContext);
		}
		request.setAttribute("video", CommonConvent.convent2EVideoData(enhancedEVideo));

		EnhancedEVideo enhancedVideoSource = null;
		if (!enhancedEVideo.isEntity()) {// 是视频集合
			enhancedEVideo = eVideoService.appendEnhancedChildren(enhancedEVideo, userContext);
			enhancedVideoSource = enhancedEVideo;
		} else {// 是单个视频体
			if (enhancedEVideo.getEnhancedParent() != null && enhancedEVideo.getEnhancedParent().getId() > 0) {// 有所属关系时
				EnhancedEVideo enhancedParentEVideo = (EnhancedEVideo) eVideoService.getEnhanced(enhancedEVideo.getEnhancedParent().getId(), userContext);
				enhancedParentEVideo = eVideoService.appendEnhancedChildren(enhancedParentEVideo, userContext);
				enhancedVideoSource = enhancedParentEVideo;
			} else {// 无所属关系时
				enhancedVideoSource = enhancedEVideo;
			}
		}
		if (userContext != null) {
			enhancedVideoSource = (EnhancedEVideo) eVideoService.appendEnhancedExtralsForUser(enhancedVideoSource, userContext);
		}

		request.setAttribute("videoSource", CommonConvent.convent2EVideoData(enhancedVideoSource));

		Pagination<EnhancedComment> enhancedHotCommentPagination = new Pagination<EnhancedComment>(1, 3, true);
		enhancedHotCommentPagination = commentService.getPaginationForHot(ItemTypeEnumForSource.VIDEO, enhancedEVideo.getId(), enhancedHotCommentPagination, userContext);

		Pagination<EnhancedComment> enhancedCommentPagination = new Pagination<EnhancedComment>(1, 10, true);
		enhancedCommentPagination = commentService.getPaginationForActive(ItemTypeEnumForSource.VIDEO, enhancedEVideo.getId(), enhancedCommentPagination, userContext);
		request.setAttribute("enhancedCommentPagination", enhancedCommentPagination);

		List<EnhancedComment> allEnhancedComments = new ArrayList<EnhancedComment>();// 所有评论
		if (Detect.notEmpty(enhancedCommentPagination.getItems())) {
			allEnhancedComments.addAll(enhancedCommentPagination.getItems());
		}
		if (Detect.notEmpty(enhancedHotCommentPagination.getItems())) {
			allEnhancedComments.addAll(enhancedHotCommentPagination.getItems());
		}
		if (Detect.notEmpty(allEnhancedComments) && userContext != null) {
			allEnhancedComments = commentService.appendEnhancedAttitude2EnhancedCommentsForUser(allEnhancedComments, userContext);
		}

		if (Detect.notEmpty(enhancedCommentPagination.getItems())) {
			request.setAttribute("comments", CommonConvent.convent2CommentDatas(enhancedCommentPagination.getItems()));
		}

		if (Detect.notEmpty(enhancedHotCommentPagination.getItems())) {
			request.setAttribute("hotComments", CommonConvent.convent2CommentDatas(enhancedHotCommentPagination.getItems()));
		}

		Pagination<? extends BaseEnhanced> relationPagination = new Pagination<EnhancedEVideo>(1, 8, false);

		relationPagination = sourceService.getPaginationForCorrelation(ItemTypeEnumForSource.VIDEO, enhancedEVideo.getId(), Arrays.asList(new ItemTypeEnumForSource[] { ItemTypeEnumForSource.VIDEO }),
				relationPagination, userContext);

		if (Detect.notEmpty(relationPagination.getItems())) {
			relationPagination.setItems((List) eVideoService.appendEnhancedChildren((List<EnhancedEVideo>) relationPagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEVideo((List<EnhancedEVideo>) relationPagination.getItems());
			request.setAttribute("relationVideos", CommonConvent.convent2EVideoDatas((List<EnhancedEVideo>) relationPagination.getItems()));
		}

		statisticsService.updateCount(ItemTypeEnumForSource.VIDEO, enhancedEVideo.getId(), Statistics.COLUMN_COUNT_WATCH, true, 1, userContext);// 更新观看总数

		return "web/video/video";
	}

	private void resetEnhancedStatistics2NotEntityEnhancedEVideo(List<EnhancedEVideo> enhancedEVideos) {
		for (EnhancedEVideo _EnhancedEVideo : enhancedEVideos) {
			if (!_EnhancedEVideo.isEntity() && Detect.notEmpty(_EnhancedEVideo.getEnhancedChildren())) {
				EnhancedStatistics enhancedStatistics = new EnhancedStatistics();
				enhancedStatistics.setItemType(ItemTypeEnumForSource.AUDIO);
				for (EnhancedEVideo _childEnhancedEVideo : _EnhancedEVideo.getEnhancedChildren()) {
					if (_childEnhancedEVideo.getEnhancedStatistics() != null) {
						enhancedStatistics.setCountComment(enhancedStatistics.getCountComment() + _childEnhancedEVideo.getEnhancedStatistics().getCountComment());
						enhancedStatistics.setCountWatch(enhancedStatistics.getCountWatch() + _childEnhancedEVideo.getEnhancedStatistics().getCountWatch());
						enhancedStatistics.setCountPraise(enhancedStatistics.getCountPraise() + _childEnhancedEVideo.getEnhancedStatistics().getCountPraise());
						enhancedStatistics.setCountFavorite(enhancedStatistics.getCountFavorite() + _childEnhancedEVideo.getEnhancedStatistics().getCountFavorite());
					}
				}
				_EnhancedEVideo.setEnhancedStatistics(enhancedStatistics);
			}
		}
	}

}
